<?php

namespace app\admin\controller\finance;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;
use app\common\library\Ems;
use think\Db;

/**
 * 支出明细
 *
 * @icon fa fa-circle-o
 */
class Spendinglog extends Backend
{

    /**
     * Spendinglog模型对象
     * @var \app\admin\model\finance\Spendinglog
     */
    protected $model = null;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'id,desc,amount';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\finance\Spendinglog;
        $this->view->assign("statusList", $this->model->getStatusList());

        //开启模型验证
        $this->modelValidate = true;

        $groupList = collection(AuthGroup::select())->toArray();
        Tree::instance()->init($groupList);
        $groupdata = [];
        $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        foreach ($result as $k => $v) {
            $groupdata[$v['id']] = $v['name'];
        }
        $this->view->assign('groupdata', $groupdata);
    }

    /**
     * 查看
     */
    public function index()
    {

        $admin = $this->auth->getUserInfo();
        $group = $this->auth->getGroups();
        $groupId = $group[0]["group_id"];
        $this->assignconfig('groupId', $groupId);
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if ($groupId == 1) {
                $list = $this->model
                    ->with(['admin', 'group', 'subjects', 'type', 'audit'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            } else if ($groupId == 2) {
                $list = $this->model
                    ->with(['admin', 'group', 'subjects', 'type', 'audit'])
                    ->where($where)
                    ->where(['h_id' => $admin["home_id"]])
                    ->order($sort, $order)
                    ->paginate($limit);
            } else if ($groupId == 3) {
                $list = $this->model
                    ->with(['admin', 'group', 'subjects', 'type', 'audit'])
                    ->where($where)
                    ->where(['u_id' => $admin["id"]])
                    ->order($sort, $order)
                    ->paginate($limit);
            }

            foreach ($list as $row) {
                $row->visible(['id', 'group_id', 'subjects_id', 'type_id', 'datatime', 'createtime', 'create_id', 'audittime', 'audit_id', 'amount', 'status', 'proofimage', 'desc', 'updatetime']);
                $row->visible(['audit']);
                $row->getRelation('audit')->visible(['nickname']);
                $row->visible(['admin']);
                $row->getRelation('admin')->visible(['nickname']);
                $row->visible(['group']);
                $row->getRelation('group')->visible(['name']);
                $row->visible(['subjects']);
                $row->getRelation('subjects')->visible(['name']);
                $row->visible(['type']);
                $row->getRelation('type')->visible(['name']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add($ids = null)
    {
        if ($ids) {
            $row = $this->model->get($ids);
            $this->view->assign("row", $row);
        }
        $admin = $this->auth->getUserInfo();

        if ($this->request->isPost()) {
            // $params = $this->request->post("row/a");
            // $params['createtime'] = time();
            // $params['datatime'] = strtotime( $params['datatime']);
            // $add = $this->model->insert($params);
            // if ($add) {
            //     $this->success('添加成功');
            // } else {
            //     $this->error('添加失败');
            // };


            $home = Db::table('jc_family_home')->where('id', '=', $admin["home_id"])->select();
            $homeAdmin = Db::table('jc_admin')->where('id', '=', $home[0]["home_ad_id"])->select();

            //家庭本月收入
            $total1 = \app\admin\model\finance\Incomelog::where(['status' => 'audited'])->whereTime('datatime', 'month')->where(['h_id' => $admin["home_id"]])->sum('amount');
            //家庭本月支出
            $total2 = \app\admin\model\finance\Spendinglog::where(['status' => 'audited'])->whereTime('datatime', 'month')->where(['h_id' => $admin["home_id"]])->sum('amount');
            //个人本月收入
            $total3 = \app\admin\model\finance\Incomelog::where(['status' => 'audited'])->whereTime('datatime', 'month')->where(['u_id' => $admin["id"]])->sum('amount');
            //个人本月支出
            $total4 = \app\admin\model\finance\Spendinglog::where(['status' => 'audited'])->whereTime('datatime', 'month')->where(['u_id' => $admin["id"]])->sum('amount');

            if ($total1 != 0) {
                $percentage1 = round(($total2 / $total1) * 100, 2); // 将结果四舍五入并保留两位小数
            } else {
                $percentage1 = 0; // 避免除以零错误
            }
            if ($total3 != 0) {
                $percentage2 = round(($total4 / $total3) * 100, 2); // 将结果四舍五入并保留两位小数
            } else {
                $percentage2 = 0; // 避免除以零错误
            }

            if ($percentage1 > 60) {
                Ems::spending($homeAdmin[0]["email"], "您家庭的本月的收入为：" . $total1 . "，您家庭的本月的支出为：" . $total2 . "支出已超过收入的60%。比例为：" . $percentage1 . "%");
            }
            if ($percentage2 > 60) {
                Ems::spending($admin["email"], "您的本月的收入为：" . $total3 . "，您的本月的支出为：" . $total4 . "支出已超过收入的60%。比例为：" .  $percentage2 . "%");
            }
        }

        return parent::add();
    }
    public function spending()

    {
        $spending2=Ems::spending("1964208603@qq.com", "您的本月的收入为：");
        $this->success("Ajax请求成功", null, ['spending2' => $spending2]);
    }
}
